<template>
  <div class="category-settings">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="分类管理"
      left-text="返回"
      left-arrow
      @click-left="handleGoBack"
    />

    <!-- 类型切换标签 -->
    <van-tabs v-model:active="activeType" @change="onTypeChange">
      <van-tab title="支出分类" name="expense"></van-tab>
      <van-tab title="收入分类" name="income"></van-tab>
    </van-tabs>

    <!-- 分类列表 使用滑动删除 -->
    <div class="category-list">
      <van-cell-group inset>
        <van-swipe-cell
          v-for="item in currentCategories"
          :key="item.id"
        >
          <van-cell :title="item.name" :border="false">
            <template #icon>
              <div 
                class="category-icon-display"
                :style="{ 
                  backgroundColor: item.color ? item.color + '20' : '#f5f5f5',
                  borderColor: item.color || '#ddd'
                }"
              >
                <van-icon 
                  :name="item.icon" 
                  :color="item.color || '#666'"
                  size="20"
                />
              </div>
            </template>
            <template #right-icon>
              <span 
                v-if="item.id === 999" 
                class="system-label"
              >
                系统
              </span>
            </template>
          </van-cell>
          <template #right>
            <van-button
              v-if="item.id !== 999"
              square
              text="删除"
              type="danger"
              class="swipe-delete-button"
              @click="handleDelete(item)"
            />
          </template>
        </van-swipe-cell>
      </van-cell-group>

      <!-- 空状态 -->
      <van-empty
        v-if="currentCategories.length === 1"
        description="暂无分类，点击下方按钮添加"
      />
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom-actions">
      <van-button
        block
        round
        @click="showAddDialog = true"
        icon="plus"
        class="add-btn"
      >
        添加自定义分类
      </van-button>
    </div>

    <!-- 添加分类对话框 -->
    <van-popup v-model:show="showAddDialog" position="bottom" round>
      <div class="add-dialog">
        <h3>添加自定义分类</h3>
        <van-form @submit="handleAdd">
          <van-field
            v-model="newCategory.name"
            name="name"
            label="分类名称"
            placeholder="请输入分类名称"
            :rules="[{ required: true, message: '请输入分类名称' }]"
          />
          
          <!-- Vant图标选择器 -->
          <div class="icon-picker">
            <div class="icon-label">选择图标：</div>
            <div class="icon-list">
              <div
                v-for="iconItem in commonVantIcons"
                :key="iconItem.name"
                class="icon-item"
                @click="selectIcon(iconItem)"
                :class="{ active: newCategory.icon === iconItem.name }"
              >
                <van-icon 
                  :name="iconItem.name" 
                  :color="iconItem.color"
                  size="22"
                />
              </div>
            </div>
          </div>

          <div class="dialog-buttons">
            <van-button block @click="showAddDialog = false">取消</van-button>
            <van-button block type="primary" native-type="submit">
              确定
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showConfirmDialog } from 'vant';
import {
  categories,
  addCustomCategory,
  removeCategory,
  resetAllCategories,
  baseExpenseCategories,
  baseIncomeCategories
} from '@/utils/categoryData';

const router = useRouter();

// 状态管理
const activeType = ref('expense');
const showAddDialog = ref(false);
const newCategory = ref({
  name: '',
  icon: '',
  color: '#666'
});

// Vant图标列表（根据activeType动态调整）
const commonVantIcons = computed(() => {
  if (activeType.value === 'expense') {
    return [
      { name: 'hot-o', color: '#FF6B6B' },
      { name: 'shopping-cart-o', color: '#4ECDC4' },
      { name: 'bag-o', color: '#95E1D3' },
      { name: 'logistics', color: '#F38181' },
      { name: 'home-o', color: '#A8E6CF' },
      { name: 'phone-o', color: '#FFD93D' },
      { name: 'bullhorn-o', color: '#C3B1E1' },
      { name: 'fire-o', color: '#FF8B94' },
      { name: 'music-o', color: '#9BDE7E' },
      { name: 'video-o', color: '#87CEEB' },
      { name: 'medal-o', color: '#FFB6C1' },
      { name: 'bookmark-o', color: '#DDA15E' },
      { name: 'flower-o', color: '#A8E6CF' },
      { name: 'smile-o', color: '#FFD93D' },
      { name: 'coffee-o', color: '#8B4513' },
      { name: 'umbrella-circle', color: '#4682B4' }
    ];
  } else {
    return [
      { name: 'balance-pay', color: '#6BCF7F' },
      { name: 'gold-coin-o', color: '#FFB347' },
      { name: 'chart-trending-o', color: '#4A90E2' },
      { name: 'gift-o', color: '#FF6B9D' },
      { name: 'balance-o', color: '#B4A7D6' },
      { name: 'award-o', color: '#F4A261' },
      { name: 'diamond-o', color: '#8ECAE6' },
      { name: 'star-o', color: '#FFD700' },
      { name: 'like-o', color: '#FF69B4' },
      { name: 'thumb-circle-o', color: '#98D8C8' },
      { name: 'good-job-o', color: '#A8DADC' },
      { name: 'certificate', color: '#E63946' },
      { name: 'underway-o', color: '#9370DB' },
      { name: 'cash-back-record', color: '#32CD32' },
      { name: 'exchange', color: '#FF8C00' },
      { name: 'coupon-o', color: '#DC143C' }
    ];
  }
});

// 当前类型的分类列表（排除设置按钮）
const currentCategories = computed(() => {
  return categories.value[activeType.value];
});

// 切换类型
const onTypeChange = (name) => {
  activeType.value = name;
};

// 返回
const handleGoBack = () => {
  router.back();
};

// 选择图标
const selectIcon = (iconItem) => {
  newCategory.value.icon = iconItem.name;
  newCategory.value.color = iconItem.color;
};

// 添加自定义分类
const handleAdd = () => {
  if (!newCategory.value.name || !newCategory.value.icon) {
    showToast('请填写完整信息');
    return;
  }

  try {
    // 生成新的ID（使用时间戳确保唯一）
    const newId = Date.now();
    
    const category = {
      id: newId,
      name: newCategory.value.name,
      icon: newCategory.value.icon,
      color: newCategory.value.color
    };

    addCustomCategory(activeType.value, category);
    
    showToast('添加成功');
    
    // 重置表单
    newCategory.value = { name: '', icon: '', color: '#666' };
    showAddDialog.value = false;
  } catch (error) {
    console.error('添加分类失败:', error);
    showToast(error.message || '添加失败');
  }
};

// 删除分类
const handleDelete = (item) => {
  // 判断是否是基础分类
  const isBaseExpense = baseExpenseCategories.some(cat => cat.id === item.id);
  const isBaseIncome = baseIncomeCategories.some(cat => cat.id === item.id);
  const isBaseCategory = isBaseExpense || isBaseIncome;

  const message = isBaseCategory
    ? `确定要删除基础分类"${item.name}"吗？\n（可通过"恢复默认分类"恢复）`
    : `确定要删除自定义分类"${item.name}"吗？\n（删除后无法恢复）`;

  showConfirmDialog({
    title: '删除确认',
    message: message,
    confirmButtonText: '删除',
    confirmButtonColor: '#ee0a24',
  })
    .then(() => {
      try {
        removeCategory(activeType.value, item.id);
        showToast('删除成功');
      } catch (error) {
        console.error('删除分类失败:', error);
        showToast(error.message || '删除失败');
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 恢复所有默认分类
const handleResetAll = () => {
  showConfirmDialog({
    title: '恢复确认',
    message: '确定要恢复所有默认分类吗？\n自定义分类将被清空',
    confirmButtonText: '确定',
    confirmButtonColor: '#ff9800',
  })
    .then(() => {
      resetAllCategories();
      showToast('已恢复默认分类');
    })
    .catch(() => {
      // 用户取消
    });
};
</script>

<style scoped>
.category-settings {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 100px;
}

/* 导航栏样式 */
:deep(.van-nav-bar) {
  background: linear-gradient(135deg, #ffd844, #ffc107);
}

:deep(.van-nav-bar__title) {
  color: #333;
  font-weight: bold;
  font-size: 18px;
}

:deep(.van-nav-bar__text) {
  color: #333;
}

:deep(.van-icon) {
  color: #333;
}

/* Tabs样式 */
:deep(.van-tabs__wrap) {
  background: linear-gradient(135deg, #ffd844, #ffc107);
  padding-bottom: 16px;
}

:deep(.van-tabs__nav) {
  background: rgba(255, 255, 255, 0.5);
  margin: 0 16px;
  border-radius: 20px;
  padding: 4px;
}

:deep(.van-tab) {
  color: rgba(0, 0, 0, 0.6);
  font-size: 15px;
  border-radius: 16px;
  transition: all 0.3s ease;
}

:deep(.van-tab--active) {
  background-color: #fff;
  color: #333;
  font-weight: 600;
}

:deep(.van-tabs__line) {
  display: none;
}

/* 分类列表 */
.category-list {
  margin-top: 16px;
  padding: 0 16px;
}

:deep(.van-cell-group--inset) {
  margin: 0;
  border-radius: 16px;
  overflow: hidden;
}

:deep(.van-cell) {
  padding: 14px 16px;
  transition: background-color 0.2s;
}

:deep(.van-cell:active) {
  background-color: #f9f9f9;
}

.category-icon-display {
  width: 38px;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  margin-right: 12px;
  border: 1.5px solid transparent;
  transition: all 0.3s ease;
}

.system-label {
  font-size: 12px;
  color: #999;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 400;
}

.swipe-delete-button {
  height: 100%;
}

/* 底部操作按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px 16px;
  background: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.add-btn {
  background: #f5f5f5;
  border: 1px solid #e0e0e0;
  color: #666;
  font-weight: 500;
  font-size: 15px;
  height: 46px;
  box-shadow: none;
  transition: all 0.3s ease;
}

.add-btn:active {
  transform: scale(0.98);
  background: #ececec;
}

/* 添加对话框 */
.add-dialog {
  padding: 20px;
  background-color: #fff;
}

.add-dialog h3 {
  margin: 0 0 20px 0;
  text-align: center;
  font-size: 18px;
  color: #323233;
}

.dialog-buttons {
  display: flex;
  gap: 10px;
  margin-top: 16px;
}

/* 图标选择器 */
.icon-picker {
  padding: 16px;
  background-color: #f7f8fa;
  border-radius: 8px;
  margin: 16px 0;
}

.icon-label {
  font-size: 14px;
  color: #646566;
  margin-bottom: 12px;
}

.icon-list {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 10px;
  max-height: 280px;
  overflow-y: auto;
  padding: 4px;
}

.icon-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  background-color: #fff;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid #e5e5e5;
  margin: 0 auto;
}

.icon-item:active {
  transform: scale(0.92);
}

.icon-item.active {
  border-color: #ffc107;
  background-color: rgba(255, 193, 7, 0.15);
  box-shadow: 0 3px 10px rgba(255, 193, 7, 0.35);
}

/* van-cell 样式优化 */
:deep(.van-cell) {
  padding: 16px;
}

:deep(.van-cell__title) {
  font-size: 16px;
}

:deep(.van-button--small) {
  height: 28px;
  padding: 0 12px;
  font-size: 12px;
}
</style>

